package ml.kupin.search.service.impl;

import ml.kupin.search.mapper.IndexItemMapper;
import ml.kupin.search.service.IndexItemService;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.common.vo.IndexItem;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品索引库管理Service
 * Created by 小柯(Allen Kerr) on 17.5.2 19:32.
 */
@Service
public class IndexItemServiceImpl implements IndexItemService {

    @Autowired
    private IndexItemMapper indexItemMapper;

    @Autowired
    private SolrServer solrServer;

    @Override
    public KuPinResult importAllItems() {
        try {
            //1. 从数据库中查询商品，获得 IndexItem 集合
            List<IndexItem> indexItems = indexItemMapper.getIndexItems();
            //2. 遍历商品列表
            for (IndexItem indexItem : indexItems) {
                //3.1 创建文档对象
                SolrInputDocument doc = new SolrInputDocument();
                //3.2 向文档对象中添加属性
                doc.addField("id", indexItem.getId());
                doc.addField("item_title", indexItem.getTitle());
                doc.addField("item_sell_point", indexItem.getSell_point());
                doc.addField("item_price", indexItem.getPrice());
                doc.addField("item_image", indexItem.getImage());
                doc.addField("item_category_name", indexItem.getCategory_name());
                //3.3 向索引库中添加文档对象
                solrServer.add(doc);
            }
            //4 提交
            solrServer.commit();
            //5.1 返回成功结果
            return KuPinResult.ok("索引库数据导入成功！");
        } catch (Exception e) {
            e.printStackTrace();
            //5.2 返回失败结果
            return KuPinResult.notOk("索引库数据导入失败！");
        }
    }
}
